package com.sherlocky.config.dao;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;

import com.rework.joss.persistence.convention.annotation.AbstractConventionDAO;
import com.rework.joss.persistence.convention.annotation.DAO;
import com.sherlocky.config.dto.ConfigDTO;

import conf.Constants;

@DAO(pojo=ConfigDTO.class, table="sh_config", mapping = { "var", "var" }, idGenerator="uuid")
public class ConfigDAO extends AbstractConventionDAO {
	
	@Cacheable(value="configCache", key="'config-'+#var")
	public String getValue(String var) {
		ConfigDTO config = (ConfigDTO)this.findById(var);
		return config == null? null : config.getValue();
	}
	
	@CacheEvict(value= "configCache", key="'config-'+#var")
	public void save(String var, String value) {
		ConfigDTO config = new ConfigDTO();
		config.setVar(var);
		config.setValue(value);
		if(this.findById(var) == null) {
			this.create(config);
		}else{
			this.update(config);
		}
		if("version".equals(var)) {
			Constants.VERSION = value;
		}
	}
	
	@CacheEvict(value= "configCache", key="'config-'+#config.var")
	public void save(ConfigDTO config) {
		if(this.findById(config.getVar()) == null) {
			this.create(config);
		}else{
			this.update(config);
		}
	}
}
